<script setup lang="ts">
import { onMounted, onBeforeUnmount } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
// 轨迹移动
import 'leaflet-polylinedecorator';
// 动态marker
import 'leaflet.animatedmarker/src/AnimatedMarker';
import { mapOptions, attribution } from '@/constants/map';
import type { LatLngExpression } from 'leaflet';
import { handleMessage } from '@/utils/globalEvent';

// leaflet 地图实例
let map: L.Map | null = null;

// 轨迹线数据
const latlngs: LatLngExpression[] = [
	[39.898457, 116.391844],
	[39.898595, 116.377947],
	[39.898341, 116.368001],
	[39.898063, 116.357144],
	[39.899095, 116.351934],
	[39.905871, 116.35067],
	[39.922329, 116.3498],
	[39.931017, 116.349671],
	[39.939104, 116.349225],
	[39.942233, 116.34991],
	[39.947263, 116.366892],
	[39.947568, 116.387537],
	[39.947764, 116.401988],
	[39.947929, 116.410824],
	[39.947558, 116.42674],
	[39.9397, 116.427338],
	[39.932404, 116.427919],
	[39.923109, 116.428377],
	[39.907094, 116.429583],
	[39.906858, 116.41404],
	[39.906622, 116.405321],
	[39.906324, 116.394954],
	[39.906308, 116.391264],
	[39.916611, 116.390748],
];

// 轨迹导航结束
const handleAnimatedmarkerEnd = () => {
	handleMessage('轨迹回显结束');
};

// 创建地图
const createMap = () => {
	// 创建地图实例
	map = L.map('leafletMap', mapOptions);
	// 加载图层
	L.tileLayer(import.meta.env.VITE_GAODE_MAP, {
		// 如果设置此项为true，则切片不会用重复填充来表示世界范围（经度-180到180之间）之外的地方
		noWrap: true,
		// 左下角版权信息
		attribution,
	}).addTo(map);

	// 1.轨迹线
	const routeLine = L.polyline(latlngs, {
		// 线宽
		weight: 8,
		// 颜色
		// color: '#FF9900',
	}).addTo(map);

	// 2.轨迹方向箭头
	(L as any)
		.polylineDecorator(routeLine, {
			// 添加模式
			patterns: [
				{
					// 模式符号的重复间隔
					repeat: 50,
					// 符号实例
					symbol: (L as any).Symbol.arrowHead({
						// 符号大小
						pixelSize: 5,
						// 不使用圆点
						polygon: false,
						// 符号样式
						pathOptions: {
							// 是否显示边线
							stroke: true,
							// 线宽
							weight: 2,
							// 颜色
							color: '#FFFFFF',
						},
					}),
				},
			],
		})
		.addTo(map);

	// 3.动态marker
	(L as any)
		.animatedMarker(routeLine.getLatLngs(), {
			// 默认为100mm
			interval: 200,
			// 开启移动状态
			autoStart: true,
			// 移动结束后回调
			onEnd: handleAnimatedmarkerEnd,
		})
		.addTo(map);
};

// 初始化地图
const initMap = () => {
	createMap();
};
// 创建地图
onMounted(() => {
	initMap();
});
// 销毁地图
onBeforeUnmount(() => {
	map?.remove();
	map = null;
});
</script>

<template>
	<div class="map-view">
		<div id="leafletMap" class="map"></div>
	</div>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
